import React from 'react'

const asyncLoadComponent = loadComponentPromise => (
    class AsyncComponent extends React.Component {
        state = {
            Component: null,
        }
        UNSAFE_componentWillMount() { // componentWillMount 
            if (this.state.Component !== null)
                return
            loadComponentPromise()
                .then(module => module.default)
                .then((Component) => {
                    this.setState({ Component })
                })
                .catch((err) => {
                    console.error(`Cannot load component in <AsyncComponent />`)
                    throw err
                })
        }
        render() {
            const { Component } = this.state
            return (Component) ? <Component {...this.props} /> : null
        }
    }
)

export default asyncLoadComponent